package com.saifan.wyy_ov.ui.home;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.common.NetFragment;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.AdvertBean;
import com.saifan.wyy_ov.data.bean.NoticeBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.data.bean.StoreBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.communitylife.ConvenienttooActivity;
import com.saifan.wyy_ov.ui.communitylife.FleamarketActivity;
import com.saifan.wyy_ov.ui.onlishop.GroupBuyActivity;
import com.saifan.wyy_ov.ui.onlishop.StoreDetailsActivity;
import com.saifan.wyy_ov.ui.property.ComplaintandadviceActivity;
import com.saifan.wyy_ov.ui.property.DecorationApplyActivity;
import com.saifan.wyy_ov.ui.property.EngagedServiceActivity;
import com.saifan.wyy_ov.ui.property.FeeQueryActivity;
import com.saifan.wyy_ov.ui.property.PhotographActivity;
import com.saifan.wyy_ov.ui.property.ProgressQueryActivity;
import com.saifan.wyy_ov.ui.property.QuestionnaireInfoActivity;
import com.saifan.wyy_ov.ui.property.RepairActivity;
import com.saifan.wyy_ov.ui.property.VisitorManageActivity;
import com.saifan.wyy_ov.ui.set.ServerSetActivity;
import com.saifan.wyy_ov.ui.view.AutoVerticalScrollTextView;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.FileUtils;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.socks.library.KLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.lightsky.infiniteindicator.InfiniteIndicatorLayout;
import cn.lightsky.infiniteindicator.slideview.BaseSliderView;
import cn.lightsky.infiniteindicator.slideview.TextSliderView;
import lomasky.ma.httpUtils.JsonUtil;
import lomasky.ma.httpUtils.ResponseBean;

import lomasky.ma.xui.CommonAdapter;
import lomasky.ma.xui.NoScrollGridView;
import lomasky.ma.xui.ViewHolderHelper;


/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-05-04 15:20
 * @descrption 主页
 */
public class HomeFragment extends NetFragment implements BaseSliderView.OnSliderClickListener, View.OnClickListener {
    private static final int GO_PHOTOGRAPH = 123;
    public View rootview;


    private boolean isLoadedAdvert;
    private boolean isLoadedNotice;
    private CommonAdapter<Object[]> adapter;
    private String picName;
    private List<AdvertBean> advertBeans = new ArrayList<AdvertBean>();
    private List<NoticeBean> noticeBeans = new ArrayList<NoticeBean>();
    private InfiniteIndicatorLayout slider;
    private NoScrollGridView grid;
    private TextView moretext;
    private ImageView moreiv;
    private LinearLayout morelayout;
    private LinearLayout photograph;
    private LinearLayout covvtool;
    private FrameLayout engagedService;
    private FrameLayout groupbuy;
    private FrameLayout mark;

    private AutoVerticalScrollTextView autoscrollview;
    private List<String> strings = new ArrayList<>();

    public static HomeFragment newInstance(int position) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putInt("position", position);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            if (!isLoadedAdvert) {
                queryAdvert();
            }
            if (!isLoadedNotice) {
                queryNotice();
            }
        } else {
            if (!isLoadedAdvert) {
                slider.stopAutoScroll();
            }

        }


    }

    void queryAdvert() {
        Map<String, Object> params = new HashMap<>();
        params.put("XMBS", getRoomInfoBean().XMBS);
        post(Api.Customer.ADVERT, params);


    }

    private void queryNotice() {


        Map<String, Object> params = new HashMap<>();
        params.put("XMBS", getRoomInfoBean().XMBS);
        params.put("Page", 0);
        post(Api.Customer.NOTICE, params);

    }


    private void initSlider() {
        if (!advertBeans.isEmpty() && advertBeans.size() > 0) {

            for (int i = 0; i < advertBeans.size(); i++) {
                TextSliderView textSliderView = new TextSliderView(getActivity());
                String ggbt = advertBeans.get(i).getGG_bt();
                if (ggbt != null && ggbt.length() > 10) {
                    ggbt = ggbt.substring(0, 9);
                }
                textSliderView.description(ggbt).image(Api.getUrlIp()  + advertBeans.get(i).getGG_TPLJ()).setScaleType(BaseSliderView.ScaleType.CenterCrop).setOnSliderClickListener(HomeFragment.this);


                if (textSliderView.getBundle() != null) {
                    textSliderView.getBundle().putInt("index", i);
                }
                slider.addSlider(textSliderView);
            }


            if (advertBeans.size() > 1)
                slider.startAutoScroll(10000);
            else {
                slider.setInfinite(false);
            }


        } else {
            slider.setBackgroundResource(R.drawable.home_ad);
        }

        isLoadedAdvert = true;
    }


    //模块名称和图标
    List<Object[]> models = new ArrayList<>();

    public void initDefaultModel() {
        models.clear();
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.property_bill;
            ob[1] = "物业账单";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.parking_card;
            ob[1] = "停车卡续费";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.engaged_service;
            ob[1] = "社区调查";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.rate_of_progress;
            ob[1] = "进度查询";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.visitor_manage;
            ob[1] = "访客管理";
            models.add(ob);
        }
    }

    public void initExtendsModel() {
        models.clear();
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.property_bill;
            ob[1] = "物业账单";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.parking_card;
            ob[1] = "停车卡续费";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.engaged_service;
            ob[1] = "社区调查";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.rate_of_progress;
            ob[1] = "进度查询";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.visitor_manage;
            ob[1] = "访客管理";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.complaint_and_advice;
            ob[1] = "投诉建议";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.report_about_the_repair;
            ob[1] = "报事报修";
            models.add(ob);
        }
        {
            Object[] ob = new Object[2];
            ob[0] = R.mipmap.decoration_apply;
            ob[1] = "装修申请";
            models.add(ob);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootview != null) {
            return rootview;
        }
        rootview = inflater.inflate(R.layout.homelayout, container, false);

        this.mark = (FrameLayout) rootview.findViewById(R.id.mark);
        this.autoscrollview = (AutoVerticalScrollTextView) rootview.findViewById(R.id.autoscrollview);

        this.groupbuy = (FrameLayout) rootview.findViewById(R.id.group_buy);
        this.engagedService = (FrameLayout) rootview.findViewById(R.id.engagedService);
        this.covvtool = (LinearLayout) rootview.findViewById(R.id.covvtool);
        this.photograph = (LinearLayout) rootview.findViewById(R.id.photograph);
        this.morelayout = (LinearLayout) rootview.findViewById(R.id.more_layout);
        this.moreiv = (ImageView) rootview.findViewById(R.id.more_iv);
        this.moretext = (TextView) rootview.findViewById(R.id.more_text);
        this.grid = (NoScrollGridView) rootview.findViewById(R.id.grid);
        this.slider = (InfiniteIndicatorLayout) rootview.findViewById(R.id.slider);

        morelayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (adapter.getData().size() == 5) {
                    initExtendsModel();
                    moretext.setText("隐藏");
                    moreiv.setImageResource(R.mipmap.arrows_up);


                } else {
                    initDefaultModel();
                    moretext.setText("查看更多");
                    moreiv.setImageResource(R.mipmap.arrows_down);

                }
                adapter.notifyDataSetChanged();
            }
        });

        slider.setIndicatorPosition(InfiniteIndicatorLayout.IndicatorPosition.Center_Bottom);
        adapter = new CommonAdapter<Object[]>(getContext(), models, R.layout.home_icon_text) {
            @Override
            public void onBind(ViewHolderHelper holder, Object[] item, int position) {
                TextView text = holder.getView(R.id.text);
                ImageView icon = holder.getView(R.id.icon);
                text.setText(item[1].toString());
                icon.setImageResource((int) (item[0]));
            }


        };
        initDefaultModel();
        grid.setAdapter(adapter);
        adapter.setData(models);
        adapter.notifyDataSetChanged();
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (((MainActivity) getActivity()).getRoomInfoBeanList().get(0).UserType == 3) {
//                    ToastUtil.showToast(getActivity(), "您的权限不能进行此操作");
                    return;
                }
                switch (position) {
                    case 0:
                        onProperty_bill();
                        break;
                    case 1:
                        onParking_card();
                        break;
                    case 2:
                        onSurvey();
                        break;
                    case 3:
                        onRate_of_progress();
                        break;
                    case 4:
                        onVisitor_manage();
                        break;
                    case 5:
                        onComplaint_and_advice();
                        break;
                    case 6:
                        onReport_about_the_repair();
                        break;
                    case 7:
                        onDecoration_apply();
                        break;


                    default:
                        break;
                }

            }
        });


        photograph.setOnClickListener(this);
        covvtool.setOnClickListener(this);
        engagedService.setOnClickListener(this);
        groupbuy.setOnClickListener(this);
        mark.setOnClickListener(this);
        autoscrollview.setOnClickListener(this);


        new Thread() {
            @Override
            public void run() {

                while (isRunning) {
                    SystemClock.sleep(5000);
                    handler.sendEmptyMessage(199);
                }
            }
        }.start();
        return rootview;

    }

    private int number = 0;
    private boolean isRunning = true;
    private Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            if (msg.what == 199) {
                autoscrollview.next();
                number++;
                if (!strings.isEmpty()) {
                    autoscrollview.setText(strings.get(number % strings.size()));
                }

            }
        }
    };

    /**
     * 物业账单
     */
    public void onProperty_bill() {

        Intent intent = new Intent(getActivity(), FeeQueryActivity.class);
        intent.putExtra(RoomInfoBean.class.getSimpleName(), getRoomInfoBean());
        KLog.d(getRoomInfoBean().toString());
        startActivity(intent);

    }

    /**
     * 停车卡续费
     */
    public void onParking_card() {

        ToastUtil.showToast(getActivity(), "停车卡续费暂未开通，敬请期待！");

    }

    /**
     * 进度查询
     */
    public void onRate_of_progress() {

        Intent intent = new Intent(getActivity(), ProgressQueryActivity.class);
        startActivity(intent);

    }


    /**
     * 社区调查
     */
    public void onSurvey() {

        Intent intent = new Intent();
        intent.setClass(getActivity(), QuestionnaireInfoActivity.class);
        startActivity(intent);
    }

    /**
     * 装修申请
     */
    public void onDecoration_apply() {

        Intent intent = new Intent(getActivity(), DecorationApplyActivity.class);
        startActivity(intent);

    }

    /**
     * 报事报修
     */
    public void onReport_about_the_repair() {

        Intent intent = new Intent(getActivity(), RepairActivity.class);
        startActivity(intent);

    }

    /**
     * 投诉建议
     */
    public void onComplaint_and_advice() {

        Intent intent = new Intent(getActivity(), ComplaintandadviceActivity.class);
        startActivity(intent);


    }

    /**
     * 访客管理
     */
    public void onVisitor_manage() {

        Intent intent = new Intent(getActivity(), VisitorManageActivity.class);
        startActivity(intent);

    }

    /**
     * 随手拍
     */
    public void onPhotograph() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 1111);

    }


    @Override
    public void onSliderClick(BaseSliderView baseSliderView) {

        int index = baseSliderView.getBundle().getInt("index");
        AdvertBean advertBean = advertBeans.get(index);
        if (advertBean != null) {
            if (advertBean.getGG_LX() == 3) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), NotificationActivity.class);
                intent.putExtra("GG_WZDZ", advertBean.getGG_WZDZ());
                startActivity(intent);

            } else if (advertBean.getGG_LX() == 4) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), NotificationActivity.class);
                intent.putExtra("GG_ZJ", advertBean.getGG_ZJ());
                startActivity(intent);

            } else if (advertBean.getGG_LX() == 2) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("ID", advertBean.getGG_DPID());
                    new GetData().getDataJson(getActivity(), Api.StoreList.STORE_INFO, jsonObject, getString(R.string.wait), new ResponseData() {
                        @Override
                        public void onSuccess(String json) {

                            List<StoreBean> list = new Gson().fromJson(json, new TypeToken<List<StoreBean>>() {
                            }.getType());

                            if (list != null && !list.isEmpty()) {
                                Intent intent = new Intent();
                                intent.setClass(getActivity(), StoreDetailsActivity.class);
                                intent.putExtra("data", list.get(0));
                                startActivity(intent);
                            }


                        }

                        @Override
                        public void onFailed(String str) {

                        }
                    });

                } catch (JSONException e) {

                }


            }
        }


    }

    public void cammerPermission(int position) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
            int checkCallPhonePermission1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED || checkCallPhonePermission1 != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, position);
                return;
            } else {

                openCamera();


            }
        } else {
            openCamera();
        }

    }

    private void openCamera() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        startActivityForResult(intent, GO_PHOTOGRAPH);
    }


    public void onClick(View view) {
        if (getRoomInfoBean().getUserType() == 3) {
            ToastUtil.showToast(getActivity(), "您的权限不能进行此操作");
            return;
        }
        int i = view.getId();
        if (i == R.id.photograph) {

            cammerPermission(GO_PHOTOGRAPH);

        } else if (i == R.id.covvtool) {
            startActivity(new Intent(getActivity(), ConvenienttooActivity.class));

        } else if (i == R.id.engagedService) {
            startActivity(new Intent(getActivity(), EngagedServiceActivity.class));

        } else if (i == R.id.group_buy) {
            startActivity(new Intent(getActivity(), GroupBuyActivity.class));

        } else if (i == R.id.mark) {
            startActivity(new Intent(getActivity(), FleamarketActivity.class));

        } else if (i == R.id.autoscrollview) {
            Intent intent = new Intent(getActivity(), NoticeListActivity.class);
            intent.putExtra("NoticeBean", (Serializable) noticeBeans);
            startActivity(intent);

        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == GO_PHOTOGRAPH) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED
                    ) {
                // Permission Granted
                openCamera();


            } else {
                // Permission Denied
                Toast.makeText(getActivity(), "您的手机权限不足", Toast.LENGTH_SHORT)
                        .show();

            }
        }


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.i(resultCode + "onActivityResult");
        if (resultCode != -1) {
            return;
        }
        Bitmap bitmap = data.getParcelableExtra("data") ;
        File file = FileUtils. bitmapToFile(bitmap);
       FileUtils.toAlbum(getActivity(),file);
        Intent intent = new Intent(getActivity(), PhotographActivity.class);
        intent.putExtra("picName", file.getAbsolutePath());

        startActivity(intent);
    }

    @Override
    public void err(String e) {

        if (e.equals("404")){
            ToastUtil.showToast(getActivity(), "请设置授权项目");
            startActivity(new Intent(getActivity(),ServerSetActivity.class));
        }else {
            ToastUtil.showToast(getActivity(), e);
        }
    }

    @Override
    public void ok(ResponseBean response) {
        if (response.code == 200) {
            if (response.api.equals(Api.Customer.ADVERT)) {
                advertBeans = JsonUtil.getList(response.content, AdvertBean.class);
                initSlider();
            } else {
                noticeBeans = JsonUtil.getList(response.content, NoticeBean.class);

                for (NoticeBean noticeBean : noticeBeans) {
                    strings.add(noticeBean.getGG_bt());
                }
                if (!strings.isEmpty()) {
                    autoscrollview.setText(strings.get(0));
                }
            }

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
    }
}
